package com.itheima.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.common.constant.MessageConstant;
import com.itheima.common.constant.RedisMessageConstant;
import com.itheima.entity.Result;
import com.itheima.pojo.Member;
import com.itheima.service.MemberService;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.JedisPool;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.Map;

/**
 * @author Administrator
 * @version v1.0
 * @date 2019/10/14 21:31
 * @description TODO
 **/
@RestController
@RequestMapping("/login")
public class LoginController {

    public static final Logger log = Logger.getLogger(LoginController.class);

    @Reference
    private MemberService memberService;

    @Autowired
    private JedisPool jedisPool;

    @RequestMapping("/login")
    public Result check(@RequestBody Map map, HttpServletResponse response) {
        String telephone = (String) map.get("telephone");
        //获取页面上传过来的验证码
        String validateCode = (String) map.get("validateCode");
        //获取redis中存储的验证码
        String codeInRedis=jedisPool.getResource().get(telephone + RedisMessageConstant.SENDTYPE_ORDER);

        //判断用户输入的验证码和生成的验证码是否一致
        if (codeInRedis == null || !codeInRedis.equalsIgnoreCase(validateCode)) {
            //验证码错误
            return Result.error(MessageConstant.VALIDATECODE_ERROR);
        }
        //验证码正确后，判断该用户是否为会员
        Member member=memberService.findByTelephone(telephone);
        if (member == null) {
            //该用户不是会员，将用户注册到会员数据库
            member = new Member();
            member.setPhoneNumber(telephone);
            member.setRegTime(new Date());

            memberService.add(member);
        }

        //是会员，登录
        //写入cookie，下次登录就不需要再次登录
        Cookie cookie = new Cookie("login_member_telephone", telephone);
        cookie.setPath("/");//路径
        cookie.setMaxAge(60*60*24*30);//有效期30天
        response.addCookie(cookie);
        return Result.success(MessageConstant.LOGIN_SUCCESS);

    }


}